package top.txl.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.txl.Dto.RawDataDO;
import top.txl.Dto.WechatUserDO;
import top.txl.entity.R;
import top.txl.service.LoginService;
import top.txl.utils.JwtUtils;
import top.txl.utils.WeChatUtil;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/wx")
public class LoginController {

    @Autowired
    private LoginService loginService;
    
    @PostMapping("/login")
    public R user_login(@RequestBody RawDataDO rawDataDO) {
        // 用户非敏感信息：rawData
        // 签名：signature
        JSONObject rawDataJson = JSON.parseObject(rawDataDO.getRawData());
        // 1.接收小程序发送的code
        // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
        JSONObject SessionKeyOpenId = WeChatUtil.getSessionKeyOrOpenId(rawDataDO.getCode());
        // 3.接收微信接口服务 获取返回的参数
        String openid = SessionKeyOpenId.getString("openid");



        String sessionKey = SessionKeyOpenId.getString("session_key");

        // 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
        String signature2 = DigestUtils.sha1Hex(rawDataDO.getRawData() + sessionKey);
        if (!rawDataDO.getSignature().equals(signature2)) {
            return R.error("签名校验失败");
        }
        // 5.根据返回的User实体类，判断用户是否是新用户，是的话，将用户信息存到数据库；
        WechatUserDO user = loginService.findUser(openid);


        if (user == null) {
            Map map = new HashMap();
            map.put("id",openid);
            // 生成token
            String token = JwtUtils.createJwt(map);

            // 用户信息入库
            String nickName = rawDataJson.getString("nickName");
            String avatarUrl = rawDataJson.getString("avatarUrl");
            user = new WechatUserDO();
            user.setOpenId(openid);
            user.setAvatarUrl(avatarUrl);
            user.setNickname(nickName);
            user.setToken(token);
            user.setCreatedAt(LocalDateTime.now());
            user.setUpdatedAt(LocalDateTime.now());
            loginService.save(user);
        }
        if(user != null){
            user.setOpenId(null);
        }
        log.info("user,{}",user);
        return R.success(user);
    }

}

